<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>人脸对比</title>
    <script src="./js/jquery-3.6.0.js"></script>
    <link rel="stylesheet" href="./css/index.css" />
  </head>
  <body>
    <div class="header">
      <h1>人脸对比demo,nodejs+express+科大讯飞Web API,学习使用,无其他用途</h1>
    </div>

    <!-- loading -->
    <div class="loading">
      <div class="content">
        <div class="circle-loading-svg">
          <svg height="50" width="50" viewBox="0 0 50 50">
            <circle id="circle" cx="25" cy="25" r="20" />
          </svg>
        </div>
      </div>
    </div>

    <!-- 视频画面和拍照页面 -->
    <div class="video">
      <video
        id="paizhao"
        autoplay="autoplay"
        height="400px"
        object-fit="cover"
      ></video>
      <canvas id="canvas" width="500px" height="400px"></canvas>
    </div>

    <div class="video">
      <fieldset class="upload">
        <legend>上传照片</legend>
        <div>
          <label for="upimg">上传照片:</label>
          <input
            type="file"
            id="upimg"
            accept=".jpg,.png"
            onchange="uploadImage(event)"
          />
        </div>
        <div class="preview">
          <img src="" alt="" id="img" />
        </div>
      </fieldset>

      <fieldset class="operation">
        <legend>操作</legend>
        <button id="btn">点击拍照</button>
        <button id="face">对比</button>
        <p>对比结果</p>
        <div class="res"></div>
      </fieldset>
    </div>
    <div class="footer">
      <span>作者:丝网如风</span>
      <span
        >码云地址:
        <a
          href="https://gitee.com/bugkaifa/face-comparison"
          target="_blank"
          rel="noopener noreferrer"
          >https://gitee.com/bugkaifa/face-comparison</a
        >
      </span>
    </div>
    <script>
      let video = document.getElementById("paizhao");
      let img1, img2;
      // 调用摄像头
      function getCamera() {
        const videoConstraints = {};
        const constraints = {
          video: videoConstraints,
          audio: false,
        };
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then((stream) => {
            console.log(stream);
            video.srcObject = stream;
            return navigator.mediaDevices.enumerateDevices();
          })
          .catch((error) => {
            console.error(error);
          });
      }
      5;
      getCamera();

      // 拍照截图画面
      let btn = document.getElementById("btn");
      btn.onclick = () => {
        let canvas = document.getElementById("canvas");
        canvas.getContext("2d").drawImage(video, 0, 0, 500, 400);
        img1 = canvas.toDataURL("image/jpg").split(",")[1];
      };
      // 获取当前时间
      function getTime() {
        let date = new Date(),
          year = date.getFullYear(),
          month =
            date.getMonth() + 1 < 10
              ? date.getMonth() + 1 + "0"
              : date.getMonth() + 1,
          day = date.getDate() < 10 ? date.getDate() + "0" : date.getDate(),
          HH = date.getHours() < 10 ? date.getHours() + "0" : date.getHours(),
          MM =
            date.getMinutes() < 10
              ? date.getMinutes() + "0"
              : date.getMinutes(),
          SS =
            date.getSeconds() < 10
              ? date.getSeconds() + "0"
              : date.getSeconds(),
          time = `${year}-${month}-${day} ${HH}:${MM}:${SS}`;
        return time;
      }
      // 对比
      $("#face").click(() => {
        console.log("开始对比");

        if (!img1 || !img2) {
          $(".res").append(
            `<div style='padding:3px 10px;color:red'>请上传照片并点击拍照之后再进行对比</div>`
          );
        } else {
          $(".loading").show();
          $.post("/user/faceContrast", { img1, img2 }, (res) => {
            console.log(res);
            $(".loading").hide();
            $(".res").append(
              `<div style='padding:3px 10px;color:green'>${
                res.message
              }-----${getTime()}</div>`
            );
          });
        }
      });

      // 选择图片
      function uploadImage(event) {
        let img = event.target.files[0];
        // 获取预览元素
        var imgfile = document.getElementById("img");
        imgfile.src = getFileUrl("upimg");

        // file转base64
        var reader = new FileReader();
        reader.readAsDataURL(img);
        reader.onload = function (result) {
          img2 = this.result.split(",")[1];
        };
      }

      // 创建一个新的文件url
      function getFileUrl(sourceId) {
        var url;
        if (navigator.userAgent.indexOf("MSIE") >= 1) {
          // IE
          url = document.getElementById(sourceId).value;
        } else if (navigator.userAgent.indexOf("Firefox") > 0) {
          // Firefox
          url = window.URL.createObjectURL(
            document.getElementById(sourceId).files.item(0)
          );
        } else if (navigator.userAgent.indexOf("Chrome") > 0) {
          // Chrome
          url = window.URL.createObjectURL(
            document.getElementById(sourceId).files.item(0)
          );
        }
        return url;
      }
    </script>
  </body>
</html>
